package com.facebook.app.client.presenter;

import com.facebook.app.client.ClusteringMethod;
import com.facebook.app.client.event.ClusterStrategyChosenEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.SingleSelectionModel;

public class ClusterStrategyChoicePresenter implements Presenter {
	
	public interface Display {
		Widget asWidget(SelectionModel<ClusteringMethod> selectionModel);
	}
	
	private final HandlerManager eventBus;
	private final Display view;
	
	public ClusterStrategyChoicePresenter(HandlerManager eventBus, Display view) {
		this.eventBus = eventBus;
		this.view = view;
	}
	
	@Override
	public void go(final HasWidgets container) {
		container.clear();
		container.add(view.asWidget(createSelectionModel()));
	}
	
	SingleSelectionModel<ClusteringMethod> createSelectionModel() {
		
		final SingleSelectionModel<ClusteringMethod> selectionModel = new SingleSelectionModel<ClusteringMethod>();
		
		selectionModel
		.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			@Override
			public void onSelectionChange(SelectionChangeEvent event) {
				ClusteringMethod selectedMethod = selectionModel
						.getSelectedObject();
				if (selectedMethod != null) {
					eventBus.fireEvent(new ClusterStrategyChosenEvent(selectedMethod));
				}
			}
		});
		return selectionModel;
	}

}
